package com.address.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class SocketClient {
    private Socket socket;
    public SocketClient() throws IOException {
        socket = new Socket("127.0.0.1", 9966);
        System.out.println("连接服务端成功！");
    }
    /**
     * 客户端程序
     */
    public void client() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("等待连接服务端！");
        Socket socket = new Socket("127.0.0.1", 9966);
        System.out.println("连接服务端成功！");
        while (true) {
            // 给服务端发点东西
            System.out.print("请输入：");
            String s = scanner.next();
            if ("out".equals(s)) {
                break;
            }
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(s.getBytes(StandardCharsets.UTF_8));
            byte[] bytes = new byte[1024];

            // 读一下服务端发来的东西
            InputStream inputStream = socket.getInputStream();
            int read = inputStream.read(bytes);
            System.out.println("服务端：" + new String(bytes, 0, read, Charset.defaultCharset()));
        }
    }

    public String getAddress(String address) throws IOException {

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(address.getBytes(StandardCharsets.UTF_8));
        byte[] bytes = new byte[1024];

        // 读一下服务端发来的东西
        InputStream inputStream = socket.getInputStream();
        int read = inputStream.read(bytes);
        return new String(bytes, 0, read, Charset.defaultCharset());
    }

    public void close() throws IOException {
        socket.close();
    }
    public static void main(String[] args) throws IOException {
        SocketClient tcpSocketClient = new SocketClient();
//        tcpSocketClient.client();
        System.out.println("服务端输出 ： "+tcpSocketClient.getAddress("江苏省南京市江宁区秣陵街道殷巷社区长亭街53号新城玖珑湖二期27栋1单元8层801室'"));
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
        for(int i=0;i<100;i++){
            tcpSocketClient.getAddress("江苏省南京市江宁区秣陵街道胜太社区双龙大道1539号21世纪国际公寓西区66栋1单元1403室");
        }
        date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
        tcpSocketClient.close();
    }
}